package com.lin.videospringboot.controller;
import com.lin.videospringboot.Utils.ParseJson;
import com.lin.videospringboot.been.Video;
import com.lin.videospringboot.been.VideoComment;
import com.lin.videospringboot.config.ResourceHandler;
import com.lin.videospringboot.service.VideoCommentImpt;
import com.lin.videospringboot.service.VideoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/video")
public class VideoController {

    @Autowired
    ResourceHandler resourceHandler;

    @Autowired
    VideoServiceImpl videoService;


    @Autowired
    VideoCommentImpt videoCommentService;

    @Value("${connector.pip}")
    public void setPip(String pip) {
        VideoController.pip = pip;
    }

    static private String pip;

    @Value("${server.port}")
    public void setPport(String pport) {
        VideoController.pport = pport;
    }

    static private String pport;

    @Value("${upload.videoSrc}")
    public void setVideoSrc(String videoSrc) {
        VideoController.videoSrc = videoSrc;
    }

    static private String videoSrc;

    @RequestMapping("/upload")
    @ResponseBody
    private String uploadVideo(@RequestParam("file") MultipartFile file,@RequestParam("videoId")String videoId) {
        System.out.println(videoId);
        if (file.isEmpty()) return "上传失败，请选择文件";
        String fileName = file.getOriginalFilename();
//        保存形式为{videoId}.mp4
        String url = videoSrc+videoId+".mp4";
        File dest = new File(url);
        try {
            file.transferTo(dest);
//            修改数据库中对于的视频url
            videoService.updateVideoURL(url,new Integer(videoId));
            return "上传成功";
        } catch (IOException e) {
            System.out.println("文件上传失败");
            return "上传失败";
        }
    }

    @RequestMapping("/addVideo")
    @ResponseBody
    public int addVideo(@RequestBody String s) {
        Map<String,Object> mp = ParseJson.parseJson(s);
        String videoName = (String) mp.get("videoName");
        int userId = (int) mp.get("userId");
        Long time = (Long) mp.get("time");
        String coverURL = null;
        if(mp.get("videoCover")!=null) {
            coverURL = (String) mp.get("coverURL");
        } else {
            coverURL = "https://i0.hdslb.com/bfs/archive/d9564dbb9c1a5fd81959e703ccc112b0487686f2.jpg@672w_378h_1c";
        }

        Video video = Video.builder().videoName(videoName).dislikes(0).likes(0).userId(userId)
                        .time(time).coverURL(coverURL).views(0).build();

        return videoService.addVideo(video);
    }

    @RequestMapping("/getVideoListByUserId")
    @ResponseBody
    public List<Video> getVideoListByUserId(@RequestBody String s) {
        Map<String,Object> mp = ParseJson.parseJson(s);
        int userId = (int) mp.get("userId");
        return videoService.getVideoListByUserId(userId);
    }

    @RequestMapping("/getVideoWithURL")
    @ResponseBody
    public List<Video>  getVideoWithURL() {
        return videoService.getListWithURL();
    }

//  TODO:  通过videoId 查询数据库中video的信息
    @RequestMapping("/get")
    private String getVideo(@RequestBody String s) {
        Map<String,Object> mp = ParseJson.parseJson(s);
        int id = (int) mp.get("videoId");

        return "TODO";
    }


    @RequestMapping("/getShowVideo")
    @ResponseBody
    public String getShowVideo(@RequestBody String s) {
        Map<String,Object> mp = ParseJson.parseJson(s);
        int videoId = (int) mp.get("videoId");
        System.out.println("http://" + pip + ":" + pport + "/video/showVideo" + videoId);
        return "http://" + pip + ":" + pport + "/video/showVideo/" + videoId;
    }



//  TODO: 处理mp4请求--返回视频给前端
    @RequestMapping("/showVideo/{videoId}")
    @CrossOrigin
    public void showVideo(@PathVariable("videoId")String videoId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String path = videoSrc + videoId + ".mp4";
            Path filePath = Paths.get(path);
            if (Files.exists(filePath)) {
                System.out.println(path);
                String mimeType = Files.probeContentType(filePath);
                if (!StringUtils.isEmpty(mimeType)) {
                    response.setContentType(mimeType);
                }
                request.setAttribute(ResourceHandler.FILE_ATTR, filePath);
                resourceHandler.handleRequest(request, response);
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            }
        }catch (Exception e) {
            System.out.println("播放视频错误");
            e.printStackTrace();
        }
    }


//  TODO: 评论likes值改变
    @RequestMapping("/updateVideoLikes")
    @ResponseBody
    public int updateVideoLikes(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int videoId = (int) mp.get("videoId");
            int likes = (int) mp.get("likes");
            Video video = videoService.getVideoById(videoId);
            video.setLikes(likes);
            return videoService.updateVideo(video);
        } catch (Exception e) {
            return 0;
        }
    }

//  TODO: 评论dislikes值改变
    @RequestMapping("/updateVideoDislikes")
    @ResponseBody
    public int updataVideoDislikes(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int videoId = (int) mp.get("videoId");
            int dislikes = (int) mp.get("dislikes");
            Video video = videoService.getVideoById(videoId);
            video.setDislikes(dislikes);
            return videoService.updateVideo(video);
        } catch (Exception e) {
            return 0;
        }
    }


//  TODO: 添加一个视频评论
    @RequestMapping("/addVideoComment")
    @ResponseBody
    public String addVideoComment(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int videoId = (int) mp.get("videoId");
            String content = (String) mp.get("content");
            int userId = (int) mp.get("userId");
            Long time = (Long) mp.get("time");

            VideoComment videoComment = VideoComment.builder().videoId(videoId).content(content)
                                                .userId(userId).time(time).likes(0).dislikes(0).build();

            int res = videoCommentService.addVideoComment(videoComment);
            if(res==1) {
                return "1";
            } else {
                return "0";
            }
        }catch (Exception e) {
            return "0";
        }
    }

//    获取videoCommentList
    @RequestMapping("/getVideoCommentList")
    @ResponseBody
    public List<Map<String,Object>> getVideoCommentList(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int videoId = (int) mp.get("videoId");
            return videoCommentService.getVideoCommentListWithUserInfo(videoId);
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


//    按照videoName 进行模糊搜索
    @RequestMapping("/search")
    @ResponseBody
    public List<Video> searchLikeVideoame(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            String name = (String) mp.get("name");
            return videoService.searchVideo(name);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @RequestMapping("/updateVideoCommentLikes")
    @ResponseBody
    public int updateVideoCommentLikes(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int videoId = (int) mp.get("videoCommentId");
            int likes = (int) mp.get("likes");
            VideoComment videoComment = videoCommentService.getVideoCommentById(videoId);
            videoComment.setLikes(likes);
            return videoCommentService.updateVideoComment(videoComment);
        }catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    @RequestMapping("/updateVideoCommentDiklikes")
    @ResponseBody
    public int updateVideoCommentDislikes(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int videoCommentId = (int) mp.get("videoCommentId");
            int dislikes = (int) mp.get("dislikes");
            VideoComment videoComment = videoCommentService.getVideoCommentById(videoCommentId);
            videoComment.setDislikes(dislikes);
            return videoCommentService.updateVideoComment(videoComment);
        }catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @RequestMapping("/getVideoById")
    @ResponseBody
    public Video getVideoById(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int videoId = (int) mp.get("videoId");
            return videoService.getVideoById(videoId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
